<template>
  <div class="barrage" ref="barrage">
    <div v-for="line in lines" class="row" :key="line" ref="barrageRow">
      <template v-for="(item, index) in list" >
        <div v-if="index % lines === line - 1 " class="col" :key="item[itemKey]">
          <slot v-bind:item="item"></slot>
        </div>
      </template>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    list: {
      type: Array,
      default(){
        return []
      }
    },
    itemKey: {
      type: String,
      default: 'name'
    },
    lines: {
      type: Number,
      default: 3
    }
  },
  data(){
    return {
      containerWidth: 0,
      rollInterval: []
    }
  },
  mounted(){
    this.initRolling()
  },
  beforeDestroy(){
    this.clearRolling()
  },
  watch: {
    list(){
      this.initRolling()
    }
  },
  methods: {
    clearRolling(){
      for(let item of this.rollInterval){
        clearInterval(item)
      }
      this.rollInterval = []
    },
    initRolling(){
      this.clearRolling()
      let barrage = this.$refs.barrage;
      let barrageRow = this.$refs.barrageRow;
      if(barrage && barrageRow && barrageRow.length){
        let containDetail = barrage.getBoundingClientRect();
        this.containerWidth = containDetail.width;
        for(let item of barrageRow){
          let rowDetail = item.getBoundingClientRect();
          let rowWidth = rowDetail.width;
          let transLeft = this.containerWidth;
          item.style.left = `${transLeft}px`;
          setInterval(() => {
            if(transLeft <= -(rowWidth)){
              item.classList.remove("isRolling");
              transLeft = this.containerWidth;
            }else{
              item.classList.add("isRolling");
              transLeft -= 50;
            }
            item.style.left = `${transLeft}px`;
          }, 500)
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.barrage{
  width: 100%;
  overflow: hidden;
  .row{
    position: relative;
    left: 100%;
    white-space: nowrap;
    display:inline-block;
    &.isRolling{
      transition: all .5s linear;
    }
    .col{
      display: inline-block;
    }
  }
}
</style>